<?php

namespace app\admin\controller;

use app\api\model\Privatechat;
use think\Db;
use think\Session;
use app\api\model\Task;
use think\Cache;
use Vectorface\Whip\Whip;

class Chat extends Common
{
    public function stickerCate(): string
    {
        $where = [];

        $search_name = input('param.name');
        $search_search = input('param.search');
        if ($search_name && $search_search) {
            $where[$search_search] = ['like', '%' . $search_name . '%'];
        }

        $data = Db::name('chat_sticker_category')
            ->where($where)->order('sort desc, id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('data', $data);

        $page = $data->render();
        $this->assign('page', $page);

        return $this->fetch();
    }
    public function addStickerCate()
    {
        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            if (!$id) {
                $db = Db::name('chat_sticker_category')->insert($post);
                if ($db) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {
                $db = Db::name('chat_sticker_category')->where('id', $id)->update($post);
                if ($db !== false) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('chat_sticker_category')->find($id);
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    return ['err' => 'id参数错误'];
                }
            }

            $data = $this->fetch();
        }
        return $data;
    }
    public function delStickerCate(): array
    {
        if (request()->isAjax()) {

            $id = input('id/d');

            if ($id) {
                $result = Db::name('chat_sticker_category')->delete($id);

                $data = $result ? ['ret' => '删除成功'] : ['err' => '删除失败'];
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    public function sticker(): string
    {
        $where = ['user_id'=>0];

        $search_name = input('param.name');
        $search_search = input('param.search');
        if ($search_name && $search_search) {
            if ($search_search == 'user_id') {
                $where[$search_search] = $search_name;
            } else {
                $where[$search_search] = ['like', '%' . $search_name . '%'];
            }
        }

        $data = Db::name('chat_sticker')->master()->where($where)->order('sort desc, id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);

        return $this->fetch();
    }

    public function addSticker()
    {
        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            $image = explode('.', $post['image']);
            $post['preview'] = $image[0] . '_thumb.' . $image[1];

            if (!$id) {
                $db = Db::name('chat_sticker')->insert($post);
                if ($db) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {
                $db = Db::name('chat_sticker')->where('id', $id)->update($post);
                if ($db !== false) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            $cate = Db::name('chat_sticker_category')->select();
            $this->assign('cate', $cate);
            
            if ($id) {
                $name = Db::name('chat_sticker')->find($id);
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    return ['err' => 'id参数错误'];
                }
            }

            $data = $this->fetch();
        }
        return $data;
    }
    public function stickerNameChange()
    {
        if (request()->isAjax()) {
            $post = input('post.');

            $db = Db::name('chat_sticker')->update($post);
            if ($db !== false) {
                $data = ['ret' => '修改成功'];
            } else {
                $data = ['err' => '修改失败'];
            }
        }
        return $data;
    }

    public function delSticker(): array
    {
        if (request()->isAjax()) {

            $id = input('id/d');

            if ($id) {
                $result = Db::name('chat_sticker')->delete($id);

                $data = $result ? ['ret' => '删除成功'] : ['err' => '删除失败'];
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    public function warnWord()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.search');

        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $data = Db::name('chat_warn_word')->where($where)->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $page = $data->render();

        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }

    // 添加预警词
    public function addWarnWord()
    {
        $id = input("id");

        if (request()->isAjax()) {
            $post = input('');

            unset($post['url']);

            if (!$id) {
                $record_id = Db::name('chat_warn_word')->where(['title' => $post['title']])->value('id');
                if ($record_id) return ['err' => '预警词已存在'];

                $res = Db::name('chat_warn_word')->insert($post);

                if ($res) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {
                $record_id = Db::name('chat_warn_word')->where(['title' => $post['title']])->value('id');
                if ($record_id != $id) return ['err' => '预警词已存在'];

                $res = Db::name('chat_warn_word')->where('id', $id)->update($post);

                if ($res) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('chat_warn_word')->find($id);

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    // 删除预警词
    public function delWarnWord()
    {
        if (request()->isAjax()) {
            $pid = input('id');
            if ($pid) {
                $res = Db::name('chat_warn_word')->delete($pid);
                if ($res) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    // public function warnRecords()
    // {
    //     $where = ['t2.is_hidden' => 0];
    //     $order = input('order', 0);
    //     $orderstr = '';
    //     if($order){
    //         $orderstr = 'count desc,';
    //     }
    //     $this->assign('order',$order);

    //     $search_name = input('param.name');
    //     $search_type = input('param.search');
    //     if ($search_name && $search_type) {
    //         if ($search_type == 'id') {
    //             $where['t3.' . $search_type] = $search_name;
    //         } else {
    //             $where['t2.' . $search_type] = $search_name;
    //         }
    //     }

    //     $subQuery = Db::name('chat_warn t1')
    //         ->field('t1.*, t2.title, t2.title, t3.name nickname, t3.sex')
    //         ->join('chat_warn_word t2', 't1.word_id = t2.id')
    //         ->join('user t3', 't1.user_id = t3.id')
    //         ->where($where)
    //         ->order('t1.id desc')
    //         ->fetchSql(true)
    //         ->select();

    //     $data = Db::table("($subQuery) a")
    //         ->field('*, count(id) as count')
    //         ->group('a.user_id,a.title')
    //         ->order($orderstr . 'id desc')
    //         ->paginate(_getCachePages(), false, ['query' => request()->param()]);

    //     $this->assign('data', $data);
    //     $page = $data->render();
    //     $this->assign('page', $page);

    //     return $this->fetch();
    // }
    
    
    
    
        public function warnRecords()
    {
        $where = ['t2.is_hidden' => 0];
        $order = input('order', 0);
        $orderstr = '';
        if($order){
            $orderstr = 'count desc,';
        }
        $this->assign('order',$order);
        $search_name = input('param.name');
        $search_type = input('param.search');
        $warn_level = input('param.warn_level');
           $this->assign('warn_level',$warn_level);
        if ($search_name && $search_type) {
            if ($search_type == 'id') {
                $where['t3.' . $search_type] = $search_name;
            } else {
                $where['t2.' . $search_type] = $search_name;
            }
        }
        if ($warn_level == 2){
            $where['t1.word_id' ] = ['in',[46,47,48,49,50]];
            $where['t1.is_banned' ] = 0;
        }
        $subQuery = Db::name('chat_warn t1')
            ->field('t1.*, t2.title, t2.title, t3.name nickname, t3.sex')
            ->join('chat_warn_word t2', 't1.word_id = t2.id')
            ->join('user t3', 't1.user_id = t3.id')
            ->where($where)
            ->order('t1.id desc')
            ->fetchSql(true)
            ->select();
        $data = Db::table("($subQuery) a")
            ->field('*, count(id) as count')
            ->group('a.user_id,a.title')
            ->order($orderstr . 'id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()])
            ->each(function($item,$key){
              if (in_array($item['word_id'],[46,47,48,49,50])){
                  $item['warn_level'] = '致命预警';
                }else{
                  $item['warn_level'] = '普通预警';
                }
                if ($item['is_banned']){
                    $item['banned_status'] = '已封禁';
                }else{
                    $item['banned_status'] = '未封禁';
                }
                return $item;
            });
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);

        return $this->fetch();
    }


    public  function  bannedUser(){
    
        $id = input('id');
              $data = ['state' => 1, 'msg' => '封禁成功'];
        if (request()->isAjax()) {
            $nowTime = time();
            $bannedInfo =  Db::name('chat_warn')->where('id', $id)->find();
           if ($bannedInfo){
               
               
               if($bannedInfo['is_banned'] == 1){
                  $data = ['state' => 0, 'msg' => '已被封禁'];
               }
               $msg = '发送致命预警词语';
           
               //注销账号
               $user = Db::name('user')->where(['id'=>$bannedInfo['user_id']])->find();
               
               Db::name('recycle_user')->insert([
                   'channel' => 1,
                   'user_id' =>$bannedInfo['user_id'],
                   'phone' =>$user['phone']??'',
                   'data' => json_encode($user),
                   'ip' => (new Whip())->getValidIpAddress(),
                   'os' => $_SERVER['HTTP_USER_AGENT'] ?? '',
                   'create_time' => $nowTime,
               ]);

               $update = [
                   'id' => $bannedInfo['user_id'],
                   'name' => '已注销',
                   'phone'=>null,
                   'wechat'=>null,
                   'qq_openID'=>null,
                   'delete_time' => $nowTime
               ];
 
               Db::name('user')->where(['id'=>$bannedInfo['user_id']])->update($update);
               Db::name('user_auth')->where(['user_id'=>$bannedInfo['user_id']])->update(['state'=>0]);
               Db::name('chat_lists')->where(['user_id'=>$bannedInfo['user_id']])->update(['another_unread'=>0]);
               Db::name('chat_lists')->where(['another_id'=>$bannedInfo['user_id']])->update(['user_unread'=>0]);
               (new \app\service\TencentIM)->account_delete($bannedInfo['user_id']);
               //冻结账号
               $banned_end_time = date('Y-m-d H:i:s', strtotime('+365 days'));
               Db::name('user')->where(['id'=>$bannedInfo['user_id']])->update(['is_banned'=>1,'banned_end_time'=>$banned_end_time,'banned_desc'=>$msg]);
               Db::name('config_personal')->where(['user_id'=>$bannedInfo['user_id']])->update(['is_read_rule'=>0]);
               $adminLog = [
                   'channel' => 3,
                   'toward' => 0,
                   'money' => 0,
                   'admin' =>$this->adminInfo['name'],
                   'user_id' => $bannedInfo['user_id'],
                   'content' => '封禁账号至' . $banned_end_time . ' 原因：' . $msg
               ];
               Db::name('admin_logs')->insert($adminLog);
               //封禁设备
               $deviceList = Db::name('user_device_records')->where(['user_id'=>$bannedInfo['user_id']])->select();
               if ($deviceList){
                   foreach ($deviceList as $key=>$val){
                       $limit_device = Db::name('limit_device')->where(['device_id'=>$val['device_id'], 'delete_time'=>0])->find();
                       if(!$limit_device){
                           Db::name('limit_device')->insertGetid(['device_id'=>$val['device_id'], 'reason'=>$msg, 'create_time' => $nowTime]);
                       }
                   }
               }
               
            //   Db::name('chat_warn')->where(['user_id'=>$bannedInfo['user_id'],'word_id'=>$bannedInfo['word_id']])->update(['is_banned'=>1]);
               Db::name('chat_warn')->where(['user_id'=>$bannedInfo['user_id'],'word_id'=>['in',[46,47,48,49,50]] ])->update(['is_banned'=>1]);

           }
        }
  
        return $data;

    }
    
    
    
    
    
    
    
    

    public function delWarnRecords()
    {
        if (request()->isAjax()) {
            $pid = input('id');
            if ($pid) {
                $res = Db::name('chat_warn')->delete($pid);
                if ($res) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    public function tipWord()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.search');

        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $sex = input('param.sex');
        if ($sex !== null) {
            $where['sex'] = $sex;
            $this->assign('sex', $sex);
        }
        $single = input('param.single');
        if ($single !== null) {
            $where['single'] = $single;
            $this->assign('single', $single);
        }

        $data = Db::name('chat_tip_word')->where($where)->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $page = $data->render();

        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }

    // 添加预警词
    public function addTipWord()
    {
        $id = input("id");

        if (request()->isAjax()) {
            $post = input('');

            unset($post['url']);

            if (!$id) {
                $record_id = Db::name('chat_tip_word')->where(['title' => $post['title']])->value('id');
                if ($record_id) return ['err' => '提醒词已存在'];

                $res = Db::name('chat_tip_word')->insert($post);

                if ($res) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {
                $record_id = Db::name('chat_tip_word')->where(['title' => $post['title']])->value('id');
                if ($record_id != $id) return ['err' => '提醒词已存在'];

                $res = Db::name('chat_tip_word')->where('id', $id)->update($post);

                if ($res) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('chat_tip_word')->find($id);

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }

    // 删除预警词
    public function delTipWord()
    {
        if (request()->isAjax()) {
            $pid = input('id');
            if ($pid) {
                $res = Db::name('chat_tip_word')->delete($pid);
                if ($res) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    
    public function greetWords()
    {
        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $order = input('order') ? input('order') : 'desc';
        if ($order == 1) {
            $order = 'desc';
        } else if ($order == 2) {
            $order = 'asc';
        }
        
        $channel = input('channel') ?: 2;
        $where['channel'] = $channel;
        
        $status = input('status') ?: 0;
        $where['status'] = $status;
        
        $data = Db::name('privatechat_greet')->where($where)->order('id', $order)->paginate(_getCachePages(), false, ['query' => request()->param()]);
        
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);

        $this->assign('channel', $channel);
        $this->assign('status', $status);
        
        return $this->fetch();
    }
    public function addGreetWords()
    {
        $id = input("id");
        
        if (request()->isAjax()) {
            $post = input('post.');
            
            if (!$id) {
                
                $res = Db::name('privatechat_greet')->insert($post);
                if ($res) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {
                $res = Db::name('privatechat_greet')->where('id', $id)->update($post);
                if ($res) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
            
        } else {
            if ($id) {
                $name = Db::name('privatechat_greet')->where('id', $id)->find();
                
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            
            $data = $this->fetch();
        }
        
        return $data;
    }
    
    public function checkGreetWords()
    {
        $id = input('id');
        
        if (request()->isAjax()) {
            
            $post = input('post.');
            
            if ($id) {
                $word = Db::name('privatechat_greet')->find($id);
                
                $db = Db::name('privatechat_greet')->where('id', $id)->update(['status' => $post['status'], 'update_time' => time(), 'shenhe_time'=>time(), 'shenhe_admin_id'=>$this->adminInfo['id']]);
                
                Cache::rm('greetword' . $word['user_id'] . '&channel1');
                Cache::rm('greetword' . $word['user_id'] . '&channel2');
                
                if ($db) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            } else {
                $data = ["err" => '参数缺失'];
            }
        }
        return $data;
    }
    
    public function delGreetWords()
    {
        if (request()->isAjax()) {
            $id = input('id');
            if ($id) {
                $word = Db::name('privatechat_greet')->find($id);
                
                if ($word) {
                    $db = Db::name('privatechat_greet')->delete($id);
    
                    Cache::rm('greetword' . $word['user_id'] . '&channel1');
                    Cache::rm('greetword' . $word['user_id'] . '&channel2');
                }
                
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }
    public function videowrong()
    {
        $where = ['t1.label'=>'Porn'];
        $order = input('order', 0);
        $orderstr = '';
        if($order){
            $orderstr = 'count desc,';
        }
        $this->assign('order',$order);

        $start = input('start');
        $end = input('end');
        $timeWhere = [];
        if ($start && $end) {
            $timeWhere['create_time'] = $where['t1.create_time'] = ['between', [strtotime($start), strtotime($end)]];
        } else if ($start && !$end) {
            $timeWhere['create_time'] = $where['t1.create_time'] = ['egt', strtotime($start)];
        } else if (!$start && $end) {
            $timeWhere['create_time'] = $where['t1.create_time'] = ['elt', strtotime($end)];
        }
        $this->assign('start', $start);
        $this->assign('end', $end);

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            if ($search_type == 'id') {
                $privacy_id = Db::name('user')->where(['authcode'=>$search_name])->cache(3600)->value('id');
                if ($privacy_id) {
                    $where['t3.' . $search_type] = ['in', [$search_name, $privacy_id]];
                } else {
                    $where['t3.' . $search_type] = $search_name;
                }
            } elseif ($search_type == 'toid') {
                $ids = Db::name('order_common')->where(['types'=>2,'user_id'=>$search_name])->column('id');
                $ids2 = Db::name('order_common')->where(['types'=>2,'data'=>['like','%another_id":'.$search_name.',"autoinc%']])->column('id');
                $ids = array_merge($ids, $ids2);
                $taskids = Db::name('shenhe_task')->where(['order_id'=>['in',$ids]])->column('task_id');
                $where['t1.taskid'] = ['in', $taskids];
            }
        }

        $subQuery = Db::name('shenhe_task_records t1')
            ->field('t1.*, t3.name nickname, t3.sex')
            ->join('user t3', 't1.userid = t3.id')
            ->where($where)
            ->order('t1.id desc')
            ->fetchSql(true)
            ->select();

        if($order){
            $data = Db::table("($subQuery) a")
                ->field('*, count(id) as count')
                ->group('a.userid')
                ->order($orderstr . 'id desc')
                ->paginate(_getCachePages(), false, ['query' => request()->param()])
                ->each(function($item, $key){
                    $item['order_id'] = Db::name('shenhe_task')->where(['task_id'=>$item['taskid']])->cache(86400)->value('order_id');
                    $order = Db::name('order_common')->where(['id'=>$item['order_id']])->find();
                    $item['touserid'] = '';
                    if ($order) {
                        $orderData = json_decode($order['data'],true);
                        $item['touserid'] = $order['user_id'] == $item['userid'] ? $orderData['another_id'] : $order['user_id'];
                    } else {
                        $chat = Db::name('privatechat')->where(['order_id'=>$item['order_id']])->cache(60)->find();
                        if ($chat) {
                            $item['touserid'] = $chat['userid'] == $item['userid'] ? $chat['touserid'] : $chat['userid'];
                        }
                    }

                    $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                    return $item;
                });
        }else{
            $data = Db::name('shenhe_task_records t1')
                ->field('t1.*, t3.name nickname, t3.sex')
                ->join('user t3', 't1.userid = t3.id')
                ->where($where)
                ->order('t1.id desc')
                ->paginate(_getCachePages(), false, ['query' => request()->param()])
                ->each(function($item, $key) use ($timeWhere) {
                    $item['count'] = Db::name('shenhe_task_records')->where(['userid'=>$item['userid'], 'label'=>'Porn'])->where($timeWhere)->cache(10)->count();
                    $item['order_id'] = Db::name('shenhe_task')->where(['task_id'=>$item['taskid']])->cache(86400)->value('order_id');
                    $order = Db::name('order_common')->where(['id'=>$item['order_id']])->find();
                    $item['touserid'] = '';
                    if ($order) {
                        $orderData = json_decode($order['data'],true);
                        $item['touserid'] = $order['user_id'] == $item['userid'] ? $orderData['another_id'] : $order['user_id'];
                    } else {
                        $chat = Db::name('privatechat')->where(['order_id'=>$item['order_id']])->cache(60)->find();
                        if ($chat) {
                            $item['touserid'] = $chat['userid'] == $item['userid'] ? $chat['touserid'] : $chat['userid'];
                        }
                    }
                    $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                    return $item;
                });
        }

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);

        return $this->fetch();
    }




    public function checkGreetWordsAll()
    {
        if (request()->isAjax()) {
            $post = input('post.');
            $type = input('type');
            if (input('?post.delAll')) {
                $post = $post['delAll'];
                $db = Db::name('privatechat_greet');
                $greets = $db->where('id', 'in', $post)->column('id,user_id');
                foreach ($post as $k => $v) {
                    Cache::rm('greetword' . $greets[$v]);
                    if ($type == 'del') {
                        $db->delete($v);
                    } else {
                        $db->where('id', $v)->update(['status'=>$type, 'update_time'=>time(), 'shenhe_time'=>time(), 'shenhe_admin_id'=>$this->adminInfo['id']]);
                    }
                }
                if ($db) {
                    $data = ['ret' => '操作成功'];
                } else {
                    $data = ['err' => '操作失败'];
                }
            } else {
                $data = ['err' => '操作失败，未选中数据'];
            }
        } else {
            $data = ['err' => '提交类型错误'];
        }
        return $data;
    }


    public function chatHeartfelt()
    {
        $search_name = input('param.name');
        $search_type = input('param.search');
        $where = [];
        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $data = Db::name('chat_heartfelt')
                    ->where($where)
                    ->order('id', 'desc')
                    ->paginate(_getCachePages(), false, ['query' => request()->param()])
                    ->each(function($item){
                        $item['content'] = $item['content'] ? json_decode($item['content']) : [];
                        return $item;
                    });
        
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }


    public function addHeartfelt()
    {
        $id = input("id");
        
        if (request()->isAjax()) {
            $post = input('post.');


            if($post['title'] == ''){
                return ['err' => '问题不能为空'];
            }
            $post['content'] = isset($post['content']) ? $post['content'] : [];
            $content = array_unique($post['content']);
            $post['content'] = [];
            foreach ($content as $key => $value) {
                if($value) {
                    $post['content'][] = $value;
                }
            }

            if(sizeof($post['content']) && sizeof($post['content']) > 1){
                $post['content'] = json_encode($post['content'], JSON_UNESCAPED_UNICODE);
            }else{
                return ['err' => '至少添加两个选项'];
            }

            
            
            if (!$id) {
                
                $res = Db::name('chat_heartfelt')->insert($post);
                if ($res) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {
                $res = Db::name('chat_heartfelt')->where('id', $id)->update($post);
                if ($res) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
            
        } else {
            $content = [];
            if ($id) {
                $name = Db::name('chat_heartfelt')->where('id', $id)->find();
                
                if ($name) {
                    $this->assign('name', $name);
                    $content = $name['content'] ? json_decode($name['content']) : [];
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $this->assign('content', $content);
            
            $data = $this->fetch();
        }
        
        return $data;
    }

    public function delHeartfelt()
    {
        if (request()->isAjax()) {
            $pid = input('id');
            if ($pid) {
                $res = Db::name('chat_heartfelt')->delete($pid);
                if ($res) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }




    public function chatScriptBox()
    {
        $search_name = input('param.name');
        $search_type = input('param.search');
        $where = [];
        if ($search_name && $search_type) {
            $where[$search_type] = ['like', '%' . $search_name . '%'];
        }

        $data = Db::name('chat_script_box')
                    ->where($where)
                    ->order('id', 'desc')
                    ->paginate(_getCachePages(), false, ['query' => request()->param()]);
        
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        return $this->fetch();
    }




    public function addScriptBox()
    {
        $id = input("id");
        
        if (request()->isAjax()) {
            $post = input('post.');


            if($post['content'] == ''){
                return ['err' => '内容不能为空'];
            }
            if (!$id) {
                
                $res = Db::name('chat_script_box')->insert($post);
                if ($res) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {
                $res = Db::name('chat_script_box')->where('id', $id)->update($post);
                if ($res) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
            
        } else {
            $content = [];
            if ($id) {
                $name = Db::name('chat_script_box')->where('id', $id)->find();
                
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $this->assign('content', $content);
            
            $data = $this->fetch();
        }
        
        return $data;
    }
    public function delScriptBox()
    {
        if (request()->isAjax()) {
            $pid = input('id');
            if ($pid) {
                $res = Db::name('chat_script_box')->delete($pid);
                if ($res) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }


    public function femalePayer()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.type');

        $state = input('state/d', 0);
        $where['state'] = $state;
        $this->assign('state', $state);

        if ($search_name && $search_type) {
            if ($search_type=='user_id') {
                $where['user_id|another_id'] = $search_name;
            }
        }

        $data = db('chat_charge_check')
                    ->master()
                    ->where($where)
                    ->order('time desc')
                    ->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $page = $data->render();

        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }

    public function femalePayerStatus($id, $state)
    {
        $res = Db::name('chat_charge_check')->where(['id'=>$id])->update(['state'=>$state, 'update_time'=>time()]);
        return ['ret'=>'操作成功'];
    }



    public function lianmaiException()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.type');

        if ($search_name && $search_type) {
            $where[$search_type] = $search_name;
        }

        $data = db('privatechat_lianmai_exception')
                    ->master()
                    ->where($where)
                    ->order('exp_count desc')
                    ->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $page = $data->render();

        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }

    public function payTip($id)
    {
        $cachekey = 'payTip'.$id;
        if (cache($cachekey)) return ['err'=>'发送频繁'];
        $record = Db::name('chat_charge_check')->find($id);
        if (!$record) return ['err'=>'记录不存在'];
        cache($cachekey, 1, 10);
        $content = "当前聊天是你付费，如要改成对方付费请点击右下方'+'->'换TA付费'按钮";
        $res = Privatechat::tip($record['another_id'], $record['user_id'], $content, '', 1, -1);
        return $res ? ['ret'=>'发送成功'] : ['err'=>'发送失败，请重试'];
    }

    public function errors()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.type');

        if ($search_name && $search_type) {
            $where[$search_type] = $search_name;
        }

        $data = db('privatechat_send_error')
                    ->master()
                    ->where($where)
                    ->order('id desc')
                    ->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $page = $data->render();

        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }

    

    public function liaoyou_rm_records()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.search');

        if ($search_name && $search_type) {
            $where[$search_type] = $search_name;
        }

        $data = Db::name('delete_liaoyou_records')->where($where)->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $page = $data->render();

        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
    }

    public function sysHiEmpty()
    {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.search');

        if ($search_name && $search_type) {
            $where[$search_type] = $search_name;
        }

        $data = Db::name('system_hi_chat_empty')->where($where)->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()]);
        $page = $data->render();

        $this->assign('data', $data);
        $this->assign('page', $page);

        return $this->fetch();
        
    }


    public function Violation(): string
    {
        $where = [];

        $search_name = input('param.name');
        $search_search = input('param.search');
        if ($search_name && $search_search) {
            $where[$search_search] = ['like', '%' . $search_name . '%'];
        }

        $data = Db::name('chat_violation')
            ->where($where)->order('id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('data', $data);

        $page = $data->render();
        $this->assign('page', $page);

        return $this->fetch();
    }
    public function addViolation()
    {
        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            if (!$id) {
                $db = Db::name('chat_violation')->insert($post);
                if ($db) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {
                $db = Db::name('chat_violation')->where('id', $id)->update($post);
                if ($db !== false) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('chat_violation')->find($id);
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    return ['err' => 'id参数错误'];
                }
            }

            $data = $this->fetch();
        }
        return $data;
    }
    public function delViolation(): array
    {
        if (request()->isAjax()) {

            $id = input('id/d');

            if ($id) {
                $result = Db::name('chat_violation')->delete($id);

                $data = $result ? ['ret' => '删除成功'] : ['err' => '删除失败'];
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }


    public function autoImgOcr()
    {
        $where = ['state'=>1];

        $search_name = input('param.name');
        $search_search = input('param.search');
        if ($search_name && $search_search) {
            $where[$search_search] = ['like', '%' . $search_name . '%'];
        }

        $data = Db::name('auto_image_ocr')
            ->where($where)->order('id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()])
            ->each(function ($item)
            {
                $item['content'] = '';
                try {
                    $item['content'] = implode(' ', json_decode($item['text'],true));
                } catch (\Exception $e) {
                    
                }
                return $item;
            });

        $this->assign('data', $data);

        $page = $data->render();
        $this->assign('page', $page);

        return $this->fetch();
    }

    public function delImage()
    {
        $id = input('id/d',0);

        $img = db('auto_image_ocr')->find($id);
        if (!$img) return ['err'=>'数据不存在'];

        if (file_exists(ROOT_PATH . $img['image'])) {
            unlink(ROOT_PATH . $img['image']);
        }
        \app\service\AliOss::delete($img['image']);

        db('auto_image_ocr')->delete($id);

        return ['ret'=>'已删除'];
    }

}
